package com.tsingtree.modular.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsingtree.base.pojo.page.LayuiPageFactory;
import com.tsingtree.base.pojo.page.LayuiPageInfo;
import com.tsingtree.modular.entity.NanMessage;
import com.tsingtree.modular.entity.NanMessageMaster;
import com.tsingtree.modular.entity.NanSellerTag;
import com.tsingtree.modular.entity.NanUser;
import com.tsingtree.modular.mapper.NanMessageMasterMapper;
import com.tsingtree.modular.model.params.NanMessageMasterParam;
import com.tsingtree.modular.model.result.NanMessageMasterResult;
import com.tsingtree.modular.service.NanMessageMasterService;
import com.tsingtree.modular.service.NanMessageService;
import com.tsingtree.modular.service.NanSellerTagService;
import com.tsingtree.modular.service.NanUserService;
import com.tsingtree.roses.core.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 站内信总览 服务实现类
 * </p>
 *
 * @author jagger
 * @since 2024-07-08
 */
@Service
public class NanMessageMasterServiceImpl extends ServiceImpl<NanMessageMasterMapper, NanMessageMaster> implements NanMessageMasterService {

    @Autowired
    private NanMessageService nanMessageService;
    @Autowired
    private NanSellerTagService nanSellerTagService;
    @Autowired
    private NanUserService nanUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(NanMessageMasterParam param){
        long count = 0;
        List<NanMessage> messages = new ArrayList<>();
        for (String s : param.getTagId().split(",")) {
            List<NanUser> users = nanUserService.list(new QueryWrapper<NanUser>()
                    .like("tag", s));
            for (NanUser obj : users) {
                messages.add(new NanMessage()
                        .setIsDel(false).setIsRead(false).setUserId(obj.getId())
                        .setName(param.getName())
                        .setContent(param.getContent()));
            }
            count = count + users.size();
        }
        param.setNum((int)count);
        NanMessageMaster entity = getEntity(param);
        this.save(entity);
        messages.forEach(message -> {
            message.setMessageMasterId(entity.getId());
        });
        nanMessageService.saveBatch(messages);
    }

    @Override
    public void delete(NanMessageMasterParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(NanMessageMasterParam param){
        NanMessageMaster oldEntity = getOldEntity(param);
        NanMessageMaster newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public NanMessageMasterResult findBySpec(NanMessageMasterParam param){
        return null;
    }

    @Override
    public List<NanMessageMasterResult> findListBySpec(NanMessageMasterParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(NanMessageMasterParam param){
        Page pageContext = getPageContext();
        IPage<NanMessageMasterResult> page = this.baseMapper.customPageList(pageContext, param);
        Map<Integer, String> tagMap = nanSellerTagService.list().stream().collect(Collectors.toMap(NanSellerTag::getId, NanSellerTag::getName));
        page.getRecords().forEach(record -> {
            String tag = record.getTagId();
            if(StringUtils.hasText(tag)){
                String[] tags = tag.split(",");
                StringBuilder names = new StringBuilder();
                for(String tagStr : tags){
                    int key = Integer.parseInt(tagStr.substring(1, tagStr.length() - 1));
                    String name = tagMap.get(key);
                    names.append(" | ").append(name);
                }
                record.setTagStr(names.substring(3));
            }
        });
        return LayuiPageFactory.createPageInfo(page);
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void del(NanMessageMaster nanMessageMaster) {
//        if(!this.remove(nanMessageMaster.setIsDel(true))){
//            throw new RuntimeException();
//        }
//        List<NanMessage> messages = nanMessageService.list(new QueryWrapper<NanMessage>().eq("message_master_id", nanMessageMaster.getId()));
//        messages.forEach(message -> message.setIsDel(true));
//        if(!CollectionUtils.isEmpty(messages)){
//            nanMessageService.updateBatchById(messages);
//        }
//    }


    private Serializable getKey(NanMessageMasterParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private NanMessageMaster getOldEntity(NanMessageMasterParam param) {
        return this.getById(getKey(param));
    }

    private NanMessageMaster getEntity(NanMessageMasterParam param) {
        NanMessageMaster entity = new NanMessageMaster();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
